import router from './router'
import { constantRoutes } from './router'
import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken, removeToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
import { getRouteIds } from '@/api/role'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login', '/register', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()
  // set page title
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const permissionRoutes = store.getters.permission_routes
  const dynamicRoutes = store.getters.dynamicRoutes
  const roleId = getToken()
  if (!permissionRoutes || permissionRoutes.length === 0) {
    // 如果固定路由还没有添加到路由对象中则先添加固定路由列表
    router.addRoutes(constantRoutes)
  }
  if (dynamicRoutes && dynamicRoutes.length > 0) {
    // 用户已登录，如果是继续进入登录页面则直接进入首页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      next()
    }
  } else {
    /* 动态路由列表尚未添加到路由对象中*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 白名单路由直接进入
      next()
    } else {
      // 用户已登录
      if (roleId) {
        // 判断sessionStorage是否已保存路由数据
        const routeIdsJson = window.sessionStorage.getItem('routeIds')
        if (routeIdsJson) {
          const routeIds = JSON.parse(routeIdsJson)
          store.dispatch('permission/generateRoutes', routeIds).then(response => {
            if (response && response.length > 0) {
              const dynamicRoutes = response
              router.addRoutes(dynamicRoutes)
              next()
            } else {
              // 拿到角色的动态路由数组为空
              window.sessionStorage.removeItem('routeData')
              Message.warning('the permission routes belong to the current role is empty')
              next()
            }
          })
        } else {
          getRouteIds(roleId).then(response => {
            if (response.status === 200 && response.data.data.length > 0) {
              const routeIds = response.data.data
              window.sessionStorage.setItem('routeIds', JSON.stringify(routeIds))
              store.dispatch('permission/generateRoutes', routeIds).then(response => {
                if (response && response.length > 0) {
                  const dynamicRoutes = response
                  router.addRoutes(dynamicRoutes)
                  next()
                } else {
                  // 拿到角色的动态路由数组为空
                  window.sessionStorage.removeItem('routeIds')
                  Message.warning('the permission routes belong to the current role is empty')
                  next()
                }
              })
            } else {
              // 获取角色动态路由失败
              window.sessionStorage.removeItem('routeIds')
              Message.warning('failed to get permission routes belong to the current role ')
              next()
            }
          }).catch(error => {
            // 调用获取角色下的动态路由列表接口失败，需要重新登录
            Message.error(error)
            removeToken()
            if (window.sessionStorage.getItem('userInfo')) {
              window.sessionStorage.removeItem('userInfo')
            // eslint-disable-next-line no-trailing-spaces
            }    
            next(`/login?redirect=${to.path}`)
            NProgress.done()
          })
        }
      } else {
      // 用户未登录，重定向到登录界面
        removeToken()
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
